package com.example.concurrentprogramming8016.CyclicBarrier;

import java.util.Enumeration;
import java.util.concurrent.*;

/**
 * @author liyanhao
 * @Date 2023-01-06 21:18
 */
public class CyclicBarrierDemo {
    //保存每个学生的平均成绩
    private ConcurrentHashMap<String, Integer> map
            = new ConcurrentHashMap<>();
    private ExecutorService threadPool = Executors.newFixedThreadPool(3);

    private CyclicBarrier cb = new CyclicBarrier(3, () -> {
        int result = 0;
        ConcurrentHashMap.KeySetView<String, Integer> setView = map.keySet();
        for (String key : setView) {
            result += map.get(key);
        }
        System.out.println("三个人的平均成绩为:" + (result / 3) + "分");
    });

    public void count() {
        for (int i = 0; i < 3; i++) {
            threadPool.execute(() -> {
                //获取学生平均成绩
                int score = (int) (Math.random() * 40 + 60);
                map.put(Thread.currentThread().getName(), score);
                System.out.println(Thread.currentThread().getName() + "同学的平均成绩为:" + score);
                //执行完await等待所有学生平均成绩都i计算完毕
                try {
                    cb.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            });

        }
    }

    public static void main(String[] args) {
        CyclicBarrierDemo cyclicBarrierDemo = new CyclicBarrierDemo();
        cyclicBarrierDemo.count();
    }
}
